package com.example.thirdhomework

import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.thirdhomework.databinding.ActivityFifthBinding
import java.util.Locale

class FifthActivity : AppCompatActivity() {
    private val binding by lazy {
        ActivityFifthBinding.inflate(layoutInflater)
    }

    var seconds = 0
    var running = false
    var wasRunning = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        Log.d("life cycle", "onCreate")

        if (savedInstanceState != null) {
            seconds = savedInstanceState.getInt("seconds")
            running = savedInstanceState.getBoolean("running")
            wasRunning = savedInstanceState.getBoolean("wasRunning")
        }

        runTime()

        binding.buttonStart.setOnClickListener {
            running = true
        }

        binding.buttonStop.setOnClickListener {
            running = false
        }

        binding.buttonRestart.setOnClickListener {
            running = true // 确保计时器停止
            seconds = 0      // 重置秒数
        }
    }

    fun runTime() {
        val handler = Handler()
        val runnable = object : Runnable {
            override fun run() {
                val hours = seconds / 3600
                val minutes = (seconds % 3600) / 60
                val secs = seconds % 60
                //格式化字符串
                binding.textView.text = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, secs)
                if (running) {
                    seconds++
                }
                handler.postDelayed(this, 1000)
            }
        }
        handler.post(runnable)
    }

    // 防止屏幕翻转后数据不能保留 状态保存
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        Log.d("life cycle", "onSaveInstanceState")

        outState.putInt("seconds", seconds)
        outState.putBoolean("running", running)
        outState.putBoolean("wasRunning", wasRunning)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("life cycle","onDestroy")
    }

    override fun onStart() {
        super.onStart()
        Log.d("life cycle","onStart")
    }

    override fun onStop() {
        super.onStop()
        Log.d("life cycle","onStop")
    }

    override fun onResume() {
        super.onResume()
        Log.d("life cycle","onResume")
        if (wasRunning){
            running = true
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d("life cycle","onPause")
        wasRunning = running
        running = false
    }
}